package com.growthgate.bootcommon.handler;

import com.growthgate.bootcommon.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应处理器
 *
 * @author GrowthGate
 * @date 2020/2/14
 */
@Slf4j
@ControllerAdvice(basePackages = "com.growthgate.bootcommon.controller")
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NotNull MethodParameter methodParameter, @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, @NotNull MethodParameter methodParameter, @NotNull MediaType mediaType,
            @NotNull Class<? extends HttpMessageConverter<?>> aClass, @NotNull ServerHttpRequest serverHttpRequest,
            @NotNull ServerHttpResponse serverHttpResponse) {
        // 统一数据处理
        if (o instanceof ResponseResult) {
            return o;
        }
        // 修改响应头
        serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return ResponseResult.success(o);
    }

}